package elasticsearch

import (
	"fmt"
	"github.com/olivere/elastic/v7"
	"go-gin-init/app/core"
	"go.uber.org/zap"
	"log"
	"os"
	"time"
)

var esClient *elastic.Client

func InitEs() {

	esConf := core.Conf.Es

	client, err := elastic.NewClient(
		// elasticsearch 服务地址，多个服务地址使用逗号分隔
		elastic.SetURL(esConf.Url),
		// 禁用客户端的自动嗅探集群，单节点的话必须设为false，否则连接不上
		elastic.SetSniff(esConf.Sniff),
		//基于http base auth验证机制的账号和密码
		//elastic.SetBasicAuth("", ""),
		// 启用gzip压缩
		elastic.SetGzip(esConf.Gzip),
		// 设置监控检查时间间隔
		elastic.SetHealthcheckInterval(time.Duration(esConf.HealthcheckInterval)*time.Second),
		// 设置请求失败最大重试次数
		elastic.SetMaxRetries(esConf.MaxRetries),
		// 设置错误日志输出
		elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC ", log.LstdFlags)),
		// 设置info日志输出
		elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags)),
	)

	if err != nil {
		fmt.Println(err)
		panic("es 连接失败")
	}

	esClient = client
	zap.L().Info("es连接成功")
}

func GetEs() *elastic.Client {
	return esClient
}
